package com.joplin.iemsdemo.manager

import android.media.AudioAttributes
import android.media.AudioFormat
import android.media.AudioManager
import android.media.AudioRecord
import android.media.AudioTrack
import android.media.MediaRecorder
import androidx.annotation.RequiresPermission
import kotlin.concurrent.thread

object IEMSManager {
    //录音来源使用通话语音，这样可以防止啸叫的同时拥有系统降噪
    private const val AUDIO_SOURCE = MediaRecorder.AudioSource.VOICE_COMMUNICATION
    // 采样频率：44100Hz是唯一目前所有Android设备都保证支持的采样频率
    private const val SAMPLE_RATE = 44100
    // 音频通道使用双声道输入
    private const val CHANNEL_IN = AudioFormat.CHANNEL_IN_STEREO
    // 音频通道使用双声道输出
    private const val CHANNEL_OUT = AudioFormat.CHANNEL_OUT_STEREO
    // PCM 16bits每个样本，所有设备保证支持
    private const val AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT

    // 录音时音频数据写入的buffer的大小
    private var recordBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_IN, AUDIO_FORMAT)
    // 播放时音频数据读取的buffer的大小
    private val trackBufferSize =
        AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNEL_OUT, AUDIO_FORMAT);

    //构建描述音频属性的对象
    private val attributes by lazy {
        AudioAttributes.Builder()
            //设置音频流的用途属性
            .setUsage(AudioAttributes.USAGE_ASSISTANT)
            //设置音频内容属性
            .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
            .build()
    }

    //构建描述音频格式的对象
    private val format = AudioFormat.Builder()
        //设置采样频率
        .setSampleRate(SAMPLE_RATE)
        //设置音频格式的编码方式
        .setEncoding(AUDIO_FORMAT)
        //设置通道掩码
        .setChannelMask(CHANNEL_OUT)
        .build()

    //控制耳返的状态
    private var isRunning = false
    //音频录制器，可以录制音频裸数据PCM
    private var audioRecorder: AudioRecord? = null
    //音频播放器，支持PCM裸数据渲染
    private var audioTrack: AudioTrack? = null

    @RequiresPermission(android.Manifest.permission.RECORD_AUDIO)
    fun start() {
        if (isRunning) return
        isRunning = true
        //初始化音频录制器
        audioRecorder = AudioRecord(
            AUDIO_SOURCE,
            SAMPLE_RATE,
            CHANNEL_IN,
            AUDIO_FORMAT,
            recordBufferSize
        )
        //初始化音频播放器
        audioTrack = AudioTrack(
            attributes,
            format,
            trackBufferSize,
            AudioTrack.MODE_STREAM,
            AudioManager.AUDIO_SESSION_ID_GENERATE
        )
        //开启线程
        thread {
            //创建字节数组存储PCM的二进制数据
            val data = ByteArray(recordBufferSize)
            //开始录制
            audioRecorder?.startRecording()
            //开始播放
            audioTrack?.play()
            while (isRunning) {
                //录音数据是根据录制缓冲区大小试试读取的
                val byteSize = audioRecorder?.read(data, 0, recordBufferSize) ?: 0
                //检查到录制数据正常
                if (byteSize >= AudioRecord.SUCCESS) {
                    //AudioTrack实时渲染刚刚录制的部分
                    audioTrack?.write(data, 0, byteSize)
                }
            }
            //释放资源
            audioRecorder?.stop()
            audioRecorder?.release()
            audioTrack?.stop()
            audioTrack?.release()
            audioRecorder = null
            audioTrack = null
        }
    }

    fun stop() {
        isRunning = false
    }
}